package com.caigou.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.caigou.bean.cms.entity.*;
import com.caigou.bean.cms.param.*;
import com.caigou.component.HtmlBuilderComponent;
import com.caigou.component.HtmlHomePageBuilderComponent;
import com.caigou.mapper.cms.*;
import com.caigou.pojo.ChannelOtherConfigData;
import com.caigou.service.GovProListService;
import com.caigou.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service("govProListService")
public class GovProListServiceImpl implements GovProListService {
    @Resource
    private GovProListExpertMapper expertMapper;

    @Resource
    private GovProListIntroGroupMapper introGroupMapper;

    @Resource
    private GovProListIntroItemMapper introItemMapper;

    @Resource
    private GovProListPrizeMapper prizeMapper;

    @Resource
    private GovProListPrizeSumMapper prizeSumMapper;

    @Resource
    private GovProListPrizeWinnerMapper prizeWinnerMapper;

    @Resource
    private GovProListPrizeYearMapper prizeYearMapper;

    @Resource
    private ChannelMapper channelMapper;

    @Resource
    private HtmlHomePageBuilderComponent htmlHomePageBuilderComponent;

    @Resource
    private HtmlBuilderComponent htmlBuilderComponent;

    public Result listIntro(){
        List<GovProListIntroGroup> introList = this.listIntroEntity();
        return Result.success(introList);
    }

    public List<GovProListIntroGroup> listIntroEntity(){
        List<GovProListIntroGroup> introList = introGroupMapper.listIntroGroup();
        for(GovProListIntroGroup introGroup:introList){
            List<GovProListIntroItem> itemList = introItemMapper.listIntroItemByIntroGroupId(introGroup.getId());
            introGroup.setItemList(itemList);
        }
        return introList;
    }

    /**
     * 保存政采榜介绍内容组
     * @param param
     * @return
     */
    @Transactional(transactionManager = "txManager", propagation = Propagation.REQUIRED, rollbackFor = { Throwable.class })
    public Result saveIntroGroup(GovProListIntroGroupParam param){
        GovProListIntroGroup introGroup = new GovProListIntroGroup();
        BeanUtil.copyProperties(param, introGroup);
        long timestamp = System.currentTimeMillis();
        Date current = new Date(timestamp);
        introGroup.setCreateTime(current);
        introGroup.setUpdateTime(current);
        Integer maxRank = introGroupMapper.selectMaxRank();
        if(introGroupMapper==null || maxRank==null){
            maxRank = 0;
        }
        introGroup.setRank(maxRank+1);
        int result = 0;
        try{
            result = introGroupMapper.insertSelective(introGroup);
        }catch(DataAccessException e){
            log.error(e.getMessage(), e);
            return Result.custom(400, "政采榜介绍内容组名称重复", "政采榜介绍内容组名称重复");
        }
        if(result>0){
            return Result.success("增加政采榜介绍内容组成功");
        }else{
            return Result.error("增加政采榜介绍内容组失败", "增加政采榜介绍内容组失败");
        }
    }

    /**
     * 删除政采榜介绍内容组
     * @param param
     * @return
     */
    @Transactional(transactionManager = "txManager", propagation = Propagation.REQUIRED, rollbackFor = { Throwable.class })
    public Result deleteIntroGroup(GovProListIntroGroupParam param){
        GovProListIntroGroup introGroup = introGroupMapper.selectByPrimaryKey(param.getId());
        if(introGroup==null){
            return Result.error("没有这个政采榜内容组","没有这个政采榜内容组");
        }
        int count = introGroupMapper.getIntroGroupCount();
        if(count<=1){
            return Result.error("只有一个政采榜内容组，禁止删除", "只有一个政采榜内容组，禁止删除");
        }
        int result = introGroupMapper.deleteByPrimaryKey(param.getId());
        if(result>0){
            //更新rank值，保证连续
            int result2 = introGroupMapper.updateRankForDelete(introGroup.getRank());
            log.info("updateRankForDelete for rank={}, result={}", introGroup.getRank(), result2);

            //删除该内容组下的段落
            int result3 = introItemMapper.deleteItemByGroupId(introGroup.getId());
            log.info("删除内容组下的所有段落，deleteItemByGroupId for introGroupId={}, result={}", introGroup.getId(), result3);

            return Result.success("删除政采榜介绍内容组成功");
        }else{
            return Result.error("删除政采榜介绍内容组失败", "删除政采榜介绍内容组失败");
        }
    }

    /**
     * 更新政采榜介绍内容组
     * @param param
     * @return
     */
    public Result updateIntroGroup(GovProListIntroGroupParam param){
        GovProListIntroGroup introGroup = new GovProListIntroGroup();
        BeanUtil.copyProperties(param, introGroup);
        introGroup.setUpdateTime(new Date(System.currentTimeMillis()));
        int result = 0;
        try{
            result = introGroupMapper.updateIntroGroup(introGroup);
        }catch(DataAccessException e){
            log.error(e.getMessage(), e);
            return Result.custom(400, "更新政采榜介绍内容组失败--名称重复", "更新政采榜介绍内容组失败--名称重复");
        }
        if(result>0){
            return Result.success("更新政采榜介绍内容组成功");
        }else{
            return Result.error("更新政采榜介绍内容组失败", "更新政采榜介绍内容组失败");
        }
    }


    /**
     * 保存政采榜介绍内容段落
     * @param param
     * @return
     */
    @Transactional(transactionManager = "txManager", propagation = Propagation.REQUIRED, rollbackFor = { Throwable.class })
    public synchronized Result saveIntroItem(GovProListIntroItemParam param){
        GovProListIntroItem introItem = new GovProListIntroItem();
        BeanUtil.copyProperties(param, introItem);
        log.info("**********rank={}, introGroupId={}", param.getRank(), param.getIntroGroupId());
        //设置大于rank的item的rank值+1
        if(param.getRank().intValue()>0) {
            int result0 = introItemMapper.incrementRankByIntroGroupIdAndRank(introItem);
        }

//        Integer maxRank = introItemMapper.selectMaxRank();
//        if(maxRank==null){
//            maxRank = 0;
//        }
        long timestamp = System.currentTimeMillis();
        Date current = new Date(timestamp);
        introItem.setCreateTime(current);
        introItem.setUpdateTime(current);
        introItem.setRank(param.getRank()+1);
        int result = introItemMapper.insertSelective(introItem);
        if(result>0){
            return Result.success("增加政采榜介绍内容段落成功");
        }else{
            return Result.error("增加政采榜介绍内容段落失败", "增加政采榜介绍内容段落失败");
        }
    }

    /**
     * 删除政采榜介绍内容段落
     * @param param
     * @return
     */
    @Transactional(transactionManager = "txManager", propagation = Propagation.REQUIRED, rollbackFor = { Throwable.class })
    public Result deleteIntroItem(GovProListIntroItemParam param){
        GovProListIntroItem introItem = introItemMapper.selectByPrimaryKey(param.getId());
        if(introItem==null){
            return Result.error("没有这个政采榜内容段落", "没有这个政采榜内容段落");
        }
        int count = introItemMapper.getItemCountByGroupId(introItem.getIntroGroupId());
        if(count<=1){
            return Result.error("只有一个政采榜内容段落，禁止删除", "只有一个政采榜内容段落，禁止删除");
        }
        int result = introItemMapper.deleteByPrimaryKey(param.getId());
        if(result>0){
            //更新rank值，保证连续
            int result2 = introItemMapper.updateRankForDelete(introItem.getIntroGroupId(), introItem.getRank());
            log.info("updateRankForDelete for rank={}, result={}", introItem.getRank(), result2);
            return Result.success("删除政采榜介绍内容段落成功");
        }else{
            return Result.error("删除政采榜介绍内容段落失败", "删除政采榜介绍内容段落失败");
        }
    }

    /**
     * 更新政采榜介绍内容段落
     * @param param
     * @return
     */
    public Result updateIntroItem(GovProListIntroItemParam param){
        GovProListIntroItem introItem = new GovProListIntroItem();
        BeanUtil.copyProperties(param, introItem);
        introItem.setUpdateTime(new Date(System.currentTimeMillis()));
        int result = introItemMapper.updateIntroItem(introItem);
        if(result>0){
            return Result.success("更新政采榜介绍内容段落成功");
        }else{
            return Result.error("更新政采榜介绍内容段落失败", "更新政采榜介绍内容段落失败");
        }
    }


    /**
     * 增加政采榜总体奖项设置
     * @param param
     * @return
     */
    @Transactional(transactionManager = "txManager", propagation = Propagation.REQUIRED, rollbackFor = { Throwable.class })
    public Result savePrizeSum(GovProListPrizeSumParam param){
        GovProListPrizeSum prizeSum = new GovProListPrizeSum();
        BeanUtil.copyProperties(param, prizeSum);
        long timestamp = System.currentTimeMillis();
        Date current = new Date(timestamp);
        prizeSum.setCreateTime(current);
        prizeSum.setUpdateTime(current);
        Integer maxRank = prizeSumMapper.selectMaxRank();
        if(maxRank==null){
            maxRank = 0;
        }
        prizeSum.setRank(maxRank+1);
        int result = 0;
        try{
            result = prizeSumMapper.insertSelective(prizeSum);
        }catch(DataAccessException e){
            log.error(e.getMessage(), e);
            if(e.getMessage().contains("Data too long")){
                return Result.custom(400, "政采榜总体奖项名称超长", "政采榜总体奖项名称超长");
            }else if(e.getMessage().contains("Duplicate entry")){
                return Result.custom(400, "政采榜总体奖项名称重复", "政采榜总体奖项名称重复");
            }else{
                return Result.custom(400, "增加政采榜总体奖项失败-数据库操作错误", "增加政采榜总体奖项失败-数据库操作错误");
            }
        }
        if(result>0){
            return Result.success("增加政采榜总体奖项设置成功");
        }else{
            return Result.custom(400, "增加政采榜总体奖项设置失败", "增加政采榜总体奖项设置失败");
        }
    }

    /**
     * 删除政采榜总体奖项设置
     * @param param
     * @return
     */
    @Transactional(transactionManager = "txManager", propagation = Propagation.REQUIRED, rollbackFor = { Throwable.class })
    public Result deletePrizeSum(GovProListPrizeSumParam param){
        GovProListPrizeSum prizeSum = prizeSumMapper.selectByPrimaryKey(param.getId());
        if(prizeSum==null){
            return Result.error("没有这个政采榜总体奖项设置", "没有这个政采榜总体奖项设置");
        }
        int result = prizeSumMapper.deleteByPrimaryKey(param.getId());
        if(result>0){
            //更新rank值，保证连续
            int result2 = prizeSumMapper.updateRankForDelete(prizeSum.getRank());
            log.info("updateRankForDelete for rank={}, result={}", prizeSum.getRank(), result2);
            return Result.success("删除政采榜总体奖项设置成功");
        }else{
            return Result.error("删除政采榜总体奖项设置失败", "删除政采榜总体奖项设置失败");
        }
    }


    /**
     * 更新政采榜总体奖项设置
     * @param param
     * @return
     */
    public Result updatePrizeSum(GovProListPrizeSumParam param){
        GovProListPrizeSum prizeSum = new GovProListPrizeSum();
        BeanUtil.copyProperties(param, prizeSum);
        prizeSum.setUpdateTime(new Date(System.currentTimeMillis()));
        int result = 0;
        try{
            result = prizeSumMapper.updatePrizeSum(prizeSum);
        }catch(DataAccessException e){
            log.error(e.getMessage(), e);
            return Result.error("更新政采榜总体奖项设置失败--名称重复", "更新政采榜总体奖项设置失败--名称重复");
        }
        if(result>0){
            return Result.success("更新政采榜总体奖项设置成功");
        }else{
            return Result.error("更新政采榜总体奖项设置失败", "更新政采榜总体奖项设置失败");
        }
    }

    /**
     * 移动政采榜总体奖项设置
     * @param param
     * @return
     */
    @Transactional(transactionManager = "txManager", propagation = Propagation.REQUIRED, rollbackFor = { Throwable.class })
    public synchronized Result movePrizeSum(GovProListPrizeSumParam param){
        GovProListPrizeSum prizeSum = prizeSumMapper.selectByPrimaryKey(param.getId());
        if(prizeSum==null){
            return Result.error("没有这个总体奖项设置", "没有这个总体奖项设置");
        }
        int toRank = param.getToRank();
        GovProListPrizeSum toPrizeSum = prizeSumMapper.getByRank(toRank);
        if(toPrizeSum==null){
            return Result.error("没有这个目标总体奖项设置", "没有这个目标总体奖项设置");
        }

        int fromRank = prizeSum.getRank();
        if(fromRank==toRank){
            return Result.error("源目标与移动目标相同，无需移动", "源目标与移动目标相同，无需移动");
        }
        prizeSum.setRank(toRank);
        prizeSum.setUpdateTime(new Date(System.currentTimeMillis()));
        int result = prizeSumMapper.updatePrizeSum(prizeSum);
//        int zero = 1/0;
        if(result>0){
            int count = 0;
            param.setFromRank(fromRank);
            if(fromRank<toRank) {//向后移动
                count = prizeSumMapper.updateRankForBack(param);
                log.info("id={}， fromRank={}， toRank={}向后移动结果={}", param.getId(), fromRank, toRank, count);
            }else if(fromRank>toRank){//向前移动
                count = prizeSumMapper.updateRankForFront(param);
                log.info("id={}， fromRank={}， toRank={}向前移动结果={}", param.getId(), fromRank, toRank, count);
            }
            if(count>0) {
                return Result.success("总体奖项设置移动成功");
            }else{
                return Result.error("总体奖项设置失败", "总体奖项设置失败");
            }
        }else{
            return Result.error("总体奖项设置移动失败", "总体奖项设置移动失败");
        }
    }

    /**
     * 列表政采榜总体奖项
     * @return
     */
    public Result listPrizeSum(){
        List<GovProListPrizeSum> list = prizeSumMapper.listPrizeSum();
        return Result.success(list);
    }

    public List<GovProListPrizeSum> listPrizeSumEntity(){
        List<GovProListPrizeSum> list = prizeSumMapper.listPrizeSum();
        return list;
    }

    public Result saveExpert(GovProListExpertParam param){
        GovProListExpert ex = new GovProListExpert();
        BeanUtil.copyProperties(param, ex);
        long timestamp = System.currentTimeMillis();
        Date current = new Date(timestamp);
        ex.setCreateTime(current);
        ex.setUpdateTime(current);
        Integer maxRank = expertMapper.selectMaxRank();
        if(maxRank==null){
            maxRank = 0;
        }
        ex.setRank(maxRank+1);
        int result = 0;
        try{
            result = expertMapper.insertSelective(ex);
        }catch(DataAccessException e){
            log.error(e.getMessage(), e);
            if(e.getMessage().contains("Data too long")){
                return Result.error("增加政采榜评委专家失败--专家名称或简介超长", "增加政采榜评委专家失败--专家名称或简介超长");
            }else{
                return Result.error("增加政采榜评委专家失败", "增加政采榜评委专家失败");
            }
        }
        if(result>0){
            return Result.success("增加政采榜评委专家成功");
        }else{
            return Result.error("增加政采榜评委专家失败", "增加政采榜评委专家失败");
        }
    }

    @Transactional(transactionManager = "txManager", propagation = Propagation.REQUIRED, rollbackFor = { Throwable.class })
    public Result deleteExpert(GovProListExpertParam param){
        GovProListExpert expert = expertMapper.selectByPrimaryKey(param.getId());
        if(expert==null){
            return Result.error("没有这个政采榜专家", "没有这个政采榜专家");
        }
        int result = expertMapper.deleteByPrimaryKey(param.getId());
        if(result>0){
            //更新rank值，保证连续
            int result2 = expertMapper.updateRankForDelete(expert.getRank());
            log.info("updateRankForDelete for rank={}, result={}", expert.getRank(), result2);
            return Result.success("删除政采榜专家成功");
        }else{
            return Result.error("删除政采榜专家失败","删除政采榜专家失败");
        }

    }

    public Result updateExpert(GovProListExpertParam param){
        GovProListExpert expert = new GovProListExpert();
        BeanUtil.copyProperties(param, expert);
        expert.setUpdateTime(new Date(System.currentTimeMillis()));
        int result = expertMapper.updateExpert(expert);
        if(result>0){
            return Result.success("更新政采榜专家成功");
        }else{
            return Result.error("更新政采榜专家失败", "更新政采榜专家失败");
        }
    }

    @Transactional(transactionManager = "txManager", propagation = Propagation.REQUIRED, rollbackFor = { Throwable.class })
    public synchronized Result moveExpert(GovProListExpertParam param){
        GovProListExpert expert = expertMapper.selectByPrimaryKey(param.getId());
        if(expert==null){
            return Result.error("没有这个专家", "没有这个专家");
        }
        int toRank = param.getToRank();
        GovProListExpert toExpert = expertMapper.getByRank(toRank);
        if(toExpert==null){
            return Result.error("没有这个专家置", "没有这个专家置");
        }

        int fromRank = expert.getRank();
        if(fromRank==toRank){
            return Result.error("源目标与移动目标相同，无需移动", "源目标与移动目标相同，无需移动");
        }
        expert.setRank(toRank);
        expert.setUpdateTime(new Date(System.currentTimeMillis()));
        int result = expertMapper.updateExpert(expert);
//        int zero = 1/0;
        if(result>0){
            int count = 0;
            param.setFromRank(fromRank);
            if(fromRank<toRank) {//向后移动
                count = expertMapper.updateRankForBack(param);
                log.info("id={}， fromRank={}， toRank={}向后移动结果={}", param.getId(), fromRank, toRank, count);
            }else if(fromRank>toRank){//向前移动
                count = expertMapper.updateRankForFront(param);
                log.info("id={}， fromRank={}， toRank={}向前移动结果={}", param.getId(), fromRank, toRank, count);
            }
            if(count>0) {
                return Result.success("专家移动成功");
            }else{
                return Result.error("专家移动失败", "专家移动失败");
            }
        }else{
            return Result.error("专家移动失败", "专家移动失败");
        }
    }

    public Result listExpert(){
        List<GovProListExpert> list = expertMapper.listExpert();
        return Result.success(list);
    }

    public List<GovProListExpert> listExpertEntity(){
        List<GovProListExpert> list = expertMapper.listExpert();
        return list;
    }

    public Result savePrizeYear(GovProListPrizeYearParam param){
        GovProListPrizeYear prizeYear = new GovProListPrizeYear();
        BeanUtil.copyProperties(param, prizeYear);
        long timestamp = System.currentTimeMillis();
        Date current = new Date(timestamp);
        prizeYear.setCreateTime(current);
        prizeYear.setUpdateTime(current);
        int result = 0;
        try{
            result = prizeYearMapper.insertSelective(prizeYear);
        }catch(DataAccessException e){
            if(e.getMessage().contains("Duplicate entry")){
                return Result.custom(400, "政采榜奖项年度重复", "政采榜奖项年度重复");
            }else {
                return Result.custom(400, "增加政采榜奖项年度失败-数据库操作错误", "增加政采榜奖项年度失败-数据库操作错误");
            }
        }
        if(result>0){
            return Result.success("增加政采榜奖项年度成功");
        }else{
            return Result.error("增加政采榜奖项年度失败", "增加政采榜奖项年度失败");
        }
    }

    public Result deletePrizeYear(GovProListPrizeYearParam param){
        GovProListPrizeYear prizeYear = prizeYearMapper.selectByPrimaryKey(param.getId());
        if(prizeYear==null){
            return Result.error("没有这个政采榜奖项年度");
        }
        //判断该奖项年度下是否有奖项
        int count = prizeMapper.getPrizeCountByPrizeYearId(param.getId());
        if(count>0){
            return Result.custom(400,"该年度下有奖项，不能删除", "该年度下有奖项，不能删除");
        }
        int result = prizeYearMapper.deleteByPrimaryKey(param.getId());
        if(result>0){
            return Result.success("删除政采榜奖项年度成功");
        }else{
            return Result.error("删除政采榜奖项年度失败", "删除政采榜奖项年度失败");
        }

    }

    public Result listPrizeYear(GovProListPrizeYearParam param){
        List<GovProListPrizeYear> list = prizeYearMapper.listPrizeYearByPrizeCategory(param.getPrizeCategory(), null);
        return Result.success(list);
    }

    public Result updatePrizeYear(GovProListPrizeYearParam param){
        GovProListPrizeYear prizeYear = new GovProListPrizeYear();
        BeanUtil.copyProperties(param, prizeYear);
        prizeYear.setUpdateTime(new Date(System.currentTimeMillis()));
        int result = 0;
        try{
            result = prizeYearMapper.updatePrizeYear(prizeYear);
        }catch(DataAccessException e){
            log.error(e.getMessage(), e);
            return Result.error("更新政采榜奖项年度失败--年度名称重复", "更新政采榜奖项年度失败--年度名称重复");
        }
        if(result>0){
            return Result.success("更新政采榜奖项年度成功");
        }else{
            return Result.error("更新政采榜奖项年度失败", "更新政采榜奖项年度失败");
        }

    }

    public List<GovProListPrizeYear> listPrizeYearByCategory(Integer prizeCategory, Integer limit){
        List<GovProListPrizeYear> list = prizeYearMapper.listPrizeYearByPrizeCategory(prizeCategory, limit);
        return list;
    }

    @Transactional(transactionManager = "txManager", propagation = Propagation.REQUIRED, rollbackFor = { Throwable.class })
    public Result savePrize(GovProListPrizeParam param){
        GovProListPrize prize = new GovProListPrize();
        BeanUtil.copyProperties(param, prize);
        long timestamp = System.currentTimeMillis();
        Date current = new Date(timestamp);
        prize.setCreateTime(current);
        prize.setUpdateTime(current);
        Integer maxRank = prizeMapper.selectMaxRank(param.getPrizeYearId());
        if(maxRank==null){
            maxRank = 0;
        }
        prize.setRank(maxRank+1);
        int result = prizeMapper.insertSelective(prize);
        if(result>0){
            return Result.success("增加政采榜奖项成功");
        }else{
            return Result.error("增加政采榜奖项失败", "增加政采榜奖项失败");
        }

    }

    @Transactional(transactionManager = "txManager", propagation = Propagation.REQUIRED, rollbackFor = { Throwable.class })
    public Result deletePrize(GovProListPrizeParam param){
        GovProListPrize prize = prizeMapper.selectByPrimaryKey(param.getId());
        if(prize==null){
            return Result.error("没有这个政采榜奖项", "没有这个政采榜奖项");
        }
        //判断该奖项下是否有获取者
        int count = prizeWinnerMapper.getWinnerCountByPrizeId(param.getId());
        if(count>0){
            return Result.custom(400, "该奖项下有获奖者，不能删除", "该奖项下有获奖者，不能删除");
        }
        int result = prizeMapper.deleteByPrimaryKey(param.getId());
        if(result>0){
            //更新rank值，保证连续
            int result2 = prizeMapper.updateRankForDelete(prize);
            log.info("updateRankForDelete for rank={}, result={}", prize.getRank(), result2);
            return Result.success("删除政采榜奖项成功");
        }else{
            return Result.error("删除政采榜奖项失败", "删除政采榜奖项失败");
        }
    }

    public Result updatePrize(GovProListPrizeParam param){
        GovProListPrize prize = new GovProListPrize();
        BeanUtil.copyProperties(param, prize);
        prize.setUpdateTime(new Date(System.currentTimeMillis()));
        int result = prizeMapper.updatePrize(prize);
        if(result>0){
            return Result.success("更新政采榜年度奖项成功");
        }else{
            return Result.error("更新政采榜年度奖项失败", "更新政采榜年度奖项失败");
        }
    }

    @Transactional(transactionManager = "txManager", propagation = Propagation.REQUIRED, rollbackFor = { Throwable.class })
    public synchronized Result movePrize(GovProListPrizeParam param){
        GovProListPrize prize = prizeMapper.selectByPrimaryKey(param.getId());
        if(prize==null){
            return Result.error("没有这个年度奖项", "没有这个年度奖项");
        }
        int toRank = param.getToRank();
        GovProListPrize toPrize = prizeMapper.getByRank(toRank, prize.getPrizeYearId());
        if(toPrize==null){
            return Result.error("没有这个年度奖项", "没有这个年度奖项");
        }

        int fromRank = prize.getRank();
        if(fromRank==toRank){
            return Result.error("源目标与移动目标相同，无需移动", "源目标与移动目标相同，无需移动");
        }
        prize.setRank(toRank);
        prize.setUpdateTime(new Date(System.currentTimeMillis()));
        int result = prizeMapper.updatePrize(prize);
//        int zero = 1/0;
        if(result>0){
            int count = 0;
            param.setFromRank(fromRank);
            param.setPrizeYearId(prize.getPrizeYearId());
            if(fromRank<toRank) {//向后移动
                count = prizeMapper.updateRankForBack(param);
                log.info("id={}， fromRank={}， toRank={}向后移动结果={}", param.getId(), fromRank, toRank, count);
            }else if(fromRank>toRank){//向前移动
                count = prizeMapper.updateRankForFront(param);
                log.info("id={}， fromRank={}， toRank={}向前移动结果={}", param.getId(), fromRank, toRank, count);
            }
            if(count>0) {
                return Result.success("年度奖项移动成功");
            }else{
                return Result.error("年度奖项移动失败", "年度奖项移动失败");
            }
        }else{
            return Result.error("年度奖项移动失败", "年度奖项移动失败");
        }
    }

    public Result listPrize(Integer prizeYearId){
        List<GovProListPrize> list = prizeMapper.listPrizeByYearId(prizeYearId);
        return Result.success(list);
    }

    public List<GovProListPrize> listPrizeEntity(Integer prizeYearId){
        List<GovProListPrize> list = prizeMapper.listPrizeByYearId(prizeYearId);
        return list;
    }

    @Transactional(transactionManager = "txManager", propagation = Propagation.REQUIRED, rollbackFor = { Throwable.class })
    public Result savePrizeWinner(GovProListPrizeWinnerParam param){
        GovProListPrizeWinner prizeWinner = new GovProListPrizeWinner();
        BeanUtil.copyProperties(param, prizeWinner);
        long timestamp = System.currentTimeMillis();
        Date current = new Date(timestamp);
        prizeWinner.setCreateTime(current);
        prizeWinner.setUpdateTime(current);
        Integer maxRank = prizeWinnerMapper.selectMaxRank(param.getPrizeId());
        if(maxRank==null){
            maxRank = 0;
        }
        prizeWinner.setRank(maxRank+1);
        int result = prizeWinnerMapper.insertSelective(prizeWinner);
        if(result>0){
            return Result.success("增加政采榜总体奖项设置成功");
        }else{
            return Result.error("增加政采榜总体奖项设置失败", "增加政采榜总体奖项设置失败");
        }
    }

    @Transactional(transactionManager = "txManager", propagation = Propagation.REQUIRED, rollbackFor = { Throwable.class })
    public Result deletePrizeWinner(GovProListPrizeWinnerParam param){
        GovProListPrizeWinner prizeWinner = prizeWinnerMapper.selectByPrimaryKey(param.getId());
        if(prizeWinner==null){
            return Result.error("没有这个政采榜获奖者");
        }
        int result = prizeWinnerMapper.deleteByPrimaryKey(param.getId());
        if(result>0){
            //更新rank值，保证连续
            int result2 = prizeWinnerMapper.updateRankForDelete(prizeWinner.getRank(), prizeWinner.getPrizeId());
            log.info("updateRankForDelete for rank={}, result={}", prizeWinner.getRank(), result2);
            return Result.success("删除政采榜获奖者成功");
        }else{
            return Result.error("删除政采榜获奖者失败", "删除政采榜获奖者失败");
        }

    }

    public Result updatePrizeWinner(GovProListPrizeWinnerParam param) {
        GovProListPrizeWinner prizeWinner = new GovProListPrizeWinner();
        BeanUtil.copyProperties(param, prizeWinner);
        prizeWinner.setUpdateTime(new Date(System.currentTimeMillis()));
        int result = prizeWinnerMapper.updatePrizeWinner(prizeWinner);
        if(result>0){
            return Result.success("更新政采榜获奖者成功");
        }else{
            return Result.error("更新政采榜获奖者失败", "更新政采榜获奖者失败");
        }

    }


    @Transactional(transactionManager = "txManager", propagation = Propagation.REQUIRED, rollbackFor = { Throwable.class })
    public synchronized Result movePrizeWinner(GovProListPrizeWinnerParam param) {
        GovProListPrizeWinner prizeWinner = prizeWinnerMapper.selectByPrimaryKey(param.getId());
        if(prizeWinner==null){
            return Result.error("没有这个获奖者", "没有这个获奖者");
        }
        int toRank = param.getToRank();
        GovProListPrizeWinner toPrizeWinner = prizeWinnerMapper.getByRank(toRank, prizeWinner.getPrizeId());
        if(toPrizeWinner==null){
            return Result.error("没有这个年获奖者", "没有这个年获奖者");
        }

        int fromRank = prizeWinner.getRank();
        if(fromRank==toRank){
            return Result.error("源目标与移动目标相同，无需移动", "源目标与移动目标相同，无需移动");
        }
        prizeWinner.setRank(toRank);
        prizeWinner.setUpdateTime(new Date(System.currentTimeMillis()));
        int result = prizeWinnerMapper.updatePrizeWinner(prizeWinner);
//        int zero = 1/0;
        if(result>0){
            int count = 0;
            param.setFromRank(fromRank);
            param.setPrizeId(prizeWinner.getPrizeId());
            if(fromRank<toRank) {//向后移动
                count = prizeWinnerMapper.updateRankForBack(param);
                log.info("id={}， fromRank={}， toRank={}向后移动结果={}", param.getId(), fromRank, toRank, count);
            }else if(fromRank>toRank){//向前移动
                count = prizeWinnerMapper.updateRankForFront(param);
                log.info("id={}， fromRank={}， toRank={}向前移动结果={}", param.getId(), fromRank, toRank, count);
            }
            if(count>0) {
                return Result.success("年度奖项移动成功");
            }else{
                return Result.error("年度奖项移动失败", "年度奖项移动失败");
            }
        }else{
            return Result.error("年度奖项移动失败", "年度奖项移动失败");
        }

    }

    public Result listPrizeWinner(Integer prizeId){
        GovProListPrize prize = prizeMapper.selectByPrimaryKey(prizeId);
        if(prize==null){
            return Result.error("没有这个年度奖项", "没有这个年度奖项");
        }
        List<GovProListPrizeWinner> list = prizeWinnerMapper.listPrizeWinnerByPrize(prize);
        return Result.success(list);
    }

    public List<GovProListPrizeWinner> listPrizeWinnerEntity(GovProListPrize prize){
        List<GovProListPrizeWinner> list = prizeWinnerMapper.listPrizeWinnerByPrize(prize);
        return list;
    }

    //获取其他配置
    public Result getOtherConfigByChannelValue(String channelValue){
        ChannelOtherConfigData data = channelMapper.loadChannelOtherConfig(channelValue);
        if(data==null){
            return Result.error("没有这个频道", "没有这个频道");
        }
        return Result.success(data);
    }

    public ChannelOtherConfigData getOtherConfigEntityByChannelValue(String channelValue){
        ChannelOtherConfigData data = channelMapper.loadChannelOtherConfig(channelValue);
        return data;
    }

    //更新其他配置
    public Result updateOtherConfig(GovProListOtherConfigParam param){
        ChannelOtherConfigData data = new ChannelOtherConfigData();
        BeanUtil.copyProperties(param, data);
        data.setChannelId(param.getChannelValue());
        int result = 0;
        try{
            result = channelMapper.updateChannelOtherConfig(data);
        }catch(DataAccessException e){
            log.error(e.getMessage(), e);
            return Result.error("更新政采榜获其他配置失败", "更新政采榜获其他配置失败");
        }
        if(result>0){
            this.buildHomePage();//重新生成政采榜首页静态页面
            return Result.success("更新政采榜其他配置成功");
        }else{
            return Result.error("更新政采榜获其他配置失败", "更新政采榜获其他配置失败");
        }
    }

    //发布政采榜页面，即生成政采榜首页静态页面
    public String buildHomePage(){
        String plateId = "112";//政采频道
        String url = htmlHomePageBuilderComponent.buildHomePageConfigHtml(plateId);
        return url;
    }

    //发布政采榜尾页
    public String buildGovFooter(){
        String url = htmlBuilderComponent.buildGovFooterHtml();
        return url;
    }

    //生成政采榜政府端奖项碎片
    public String buildGovWinner(){
        List<GovProListPrizeYear> yearList = this.listPrizeYearByCategory(1, 4);
        for(GovProListPrizeYear year:yearList){
            int prizeYearId = year.getId();
            List<GovProListPrize> prizeList = this.listPrizeEntity(prizeYearId);
            year.setPrizeList(prizeList);
            for(GovProListPrize prize:prizeList){
                List<GovProListPrizeWinner> winnerList = this.listPrizeWinnerEntity(prize);
                prize.setWinnerList(winnerList);
            }
        }
        String url = htmlBuilderComponent.buildGovProListGovList(yearList);
        return url;
    }

    //生成政采榜企业端奖项碎片
    public String buildEnterpriseWinner(){
        List<GovProListPrizeYear> yearList = this.listPrizeYearByCategory(2, 4);
        for(GovProListPrizeYear year:yearList){
            int prizeYearId = year.getId();
            List<GovProListPrize> prizeList = this.listPrizeEntity(prizeYearId);
            year.setPrizeList(prizeList);
            for(GovProListPrize prize:prizeList){
                List<GovProListPrizeWinner> winnerList = this.listPrizeWinnerEntity(prize);
                prize.setWinnerList(winnerList);
            }
        }
        String url = htmlBuilderComponent.buildGovProListEnterpriseList(yearList);
        return url;
    }

    //政采榜介绍碎片
    public String buildIntro(){
        List<GovProListIntroGroup> introGroupList = this.listIntroEntity();
        String url = htmlBuilderComponent.buildGovProListIntro(introGroupList);
        return url;
    }

    //政采榜奖项总榜
    public String buildPrizeSum(){
        long start = System.currentTimeMillis();
        List<GovProListPrizeSum> prizeSumList = this.listPrizeSumEntity();
        long db = System.currentTimeMillis();
        String url = htmlBuilderComponent.buildGovProListPrizeSum(prizeSumList);
        long end = System.currentTimeMillis();
        log.info("============政采榜总奖项数据库操作时间={}ms,freemarker生成文件时间={}ms，总时间={}ms",db-start, end-db, end-start);
        return url;
    }

    //政采榜评审专家碎片
    public String buildExpert(){
        List<GovProListExpert> expertList = this.listExpertEntity();
        String url = htmlBuilderComponent.buildGovProListExpert(expertList);
        return url;
    }

}
